#include<stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUFSIZE 1000

int main (int argc, char *argv[])
{


  if (argc != 4) {
    printf("usage: %s localdev remoteipaddr port \n", argv[0]);
    printf("eg: \n");
    printf("%s eth0 192.168.1.1 8888 \n", argv[0]);
    exit(0);
  }
  int s;
  int len;  
  struct sockaddr_in my_addr;
  struct sockaddr_in remote_addr;
  struct ifreq interface;
  strncpy(interface.ifr_ifrn.ifrn_name, argv[1], IFNAMSIZ);
  char buf[BUFSIZE];
    
    
  memset (&remote_addr, 0, sizeof (remote_addr));
  remote_addr.sin_family = AF_INET;
  remote_addr.sin_addr.s_addr = inet_addr (argv[2]);
  remote_addr.sin_port = htons (strtol(argv[3],NULL,10));

 /* memset (&my_addr, 0, sizeof (my_addr));
  my_addr.sin_family = AF_INET;
  my_addr.sin_addr.s_addr = inet_addr (argv[1]);
  my_addr.sin_port = htons (strtol(argv[3], NULL, 10));
    */
  if ((s = socket (PF_INET, SOCK_STREAM, 0)) < 0) {
      perror ("socket error");
      return 1;
  }
if (setsockopt(s, SOL_SOCKET, SO_BINDTODEVICE, \
  (char *)&interface, sizeof(interface))  < 0) {
       perror("SO_BINDTODEVICE failed");
      /* Deal with error... */
} 
 /* if (bind (s, (struct sockaddr *) &my_addr, sizeof (struct sockaddr)) < 0)
  {

      perror ("bind");

      return 1;

  }*/
  if (connect (s, (struct sockaddr *) &remote_addr, sizeof (struct sockaddr)) < 0) {
      perror ("connect error");
      return 1;

    }

  printf ("connected to server\n");
/*
  len = recv (s, buf, BUFSIZE, 0);

  buf[len] = '\0';

  printf ("%s", buf);
*/
  while (1)

    {

      printf ("Enter string to send:");

      scanf ("%s", buf);

      if (!strcmp (buf, "quit"))
			{
			
			 break;
			
			}

      len = send (s, buf, strlen (buf), 0);

      len = recv (s, buf, BUFSIZE, 0);

      buf[len] = '\0';

      printf ("received:%s\n", buf);

    }

  close (s);

  return 0;
}
